package com.zhome.gateway.filter.pre;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HtmlUtil;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import com.zhome.gateway.constants.Constants;
import com.zhome.gateway.dto.ZhomeRouteDto;
import com.zhome.gateway.enums.FilterEnum;
import com.zhome.gateway.enums.GateWayCodeEnum;
import com.zhome.gateway.filter.AbstractZhomeZuulFilter;
import com.zhome.gateway.util.RequestUtil;
import com.zhome.gateway.util.XssUtils;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletRequest;

/**
 * 进行Mock操作的过滤器
 * @author cuiyh9
 * @date 2020/5/9
 */
@Slf4j
public class XssFilter extends AbstractZhomeZuulFilter {
    @Override
    public String filterType() {
        return Constants.PRE_KEY;
    }

    @Override
    public int filterOrder() {
        return FilterEnum.MockFilterEnum.getFilterOrder();
    }

    @Override
    public boolean shouldFilter() {
        RequestContext ctx = RequestContext.getCurrentContext();
        return ctx.getBoolean(Constants.RequestContextKey.CTX_X_SUCCESSOR_CAN_EXECUTE);
    }

    @Override
    public Object run() throws ZuulException {
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        String contentType = request.getContentType();//获取contentType请求头
        String method = request.getMethod();//获取请求方法  post/get
       if(method.trim().equalsIgnoreCase(Constants.HttpConst.POST_METHOD)){
            //2 处理post请求对于multipart/form-data，直接放行
            if(contentType.trim().toLowerCase().contains(Constants.HttpConst.MULTIPART_CONTENT_TYPE)){
                return null;
            }
            String requestBody = (String)ctx.get(Constants.RequestContextKey.CTX_X_REQUEST_BODY);
            if (ObjectUtil.isEmpty(requestBody)) {
                 return null;
            }
            String filterRequestBody = XssUtils.cleanXSSHtml(requestBody);
            ctx.set(Constants.RequestContextKey.CTX_X_REQUEST_BODY, filterRequestBody);
        }
        return null;

    }


    public static void main(String[] args) {
        String cc= "h&lt;alert&lt;fdsafasd</alert>";
        cc= "(3<4";
        String tt = (String)null;
//        String filterRequestBody = HtmlUtil.filter(cc);
        String filterRequestBody = XssUtils.cleanXSSHtml(cc);
        System.out.println(filterRequestBody);
    }
}
